<template>
  <el-upload
    :class="fileList.length >= props.limit ? 'non-upload' : ''"
    v-model:file-list="fileList"
    :limit="props.limit"
    action="/prod-api/system/rest/file/v2/upload"
    list-type="picture-card"
    :data="{ fileType: props.fileType || 'shop'}"
    :headers="headers"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { Session } from '@/utils/storage';
import type { UploadProps, UploadUserFile } from 'element-plus'

const headers = {
  Authorization: `${Session.get('token')}`
}

const props = defineProps(['originFileList', 'limit', 'onChange', "fileType"])
const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

watch(props, () => {
  fileList.value = props.originFileList
})

const handleRemove: UploadProps['onRemove'] = () => {
  props.onChange(fileList.value)
}

const handleSuccess = () => {
  props.onChange(fileList.value)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.non-upload {
  ::v-deep(.el-upload) {
    display: none;
  }
}
</style>